package com.jy.appmarket.screenlock.database;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.litesuits.orm.LiteOrm;
import com.litesuits.orm.db.DataBase;
import com.litesuits.orm.db.TableManager;
import com.litesuits.orm.db.assit.QueryBuilder;

/**
 * 类说明：
 * 
 * @author jie.li
 * @date 2015-4-30
 * @version 1.0.0
 */

public class CustomMessageDB {
	private DataBase mDataBase;
	private static CustomMessageDB sInstance;
	private Object mLock = new Object();

	private CustomMessageDB(Context context) {
		mDataBase = LiteOrm.newInstance(context, DBConfig.DB_NAME);
		TableManager tm = new TableManager();
		SQLiteDatabase db = mDataBase.getWritableDatabase();
		tm.checkOrCreateTable(db, CustomMessageTb.class);
		if (db != null) {
			db.close();
		}
	}

	public static CustomMessageDB getInstance(Context context) {
		if (sInstance == null) {
			sInstance = new CustomMessageDB(context);
		}
		return sInstance;
	}

	public void save(CustomMessageTb cm) {
		synchronized (mLock) {
			mDataBase.save(cm);
		}
	}

	public void save(List<CustomMessageTb> list) {
		synchronized (mLock) {
			mDataBase.save(list);
		}
	}
	
	public List<CustomMessageTb> queryCustomMessageApp(int type) {
		ArrayList<CustomMessageTb> list = null;
		synchronized (mLock) {
			QueryBuilder qb = new QueryBuilder(CustomMessageTb.class);
			qb.where(CustomMessageTb.COL_CUSTOM_MESSAGE_TYPE + " like ?",
					new String[] { type + "" });
			list = mDataBase.query(qb);
		}
		return list;
	}

	public List<CustomMessageTb> queryAll() {
		ArrayList<CustomMessageTb> list = null;
		synchronized (mLock) {
			list = mDataBase.queryAll(CustomMessageTb.class);
		}
		return list;
	}
	
	public void deleteCustomMessageApp(CustomMessageTb app) {

		synchronized (mLock) {
			String sql = "DELETE FROM "
					+ TableManager.getTable(CustomMessageTb.class).name + " WHERE "
					+ CustomMessageTb.COL_CUSTOM_MESSAGE_TYPE + "=" + app.getType()
					+ " AND " + CustomMessageTb.COL_PKG_NAME + "='"
					+ app.getPkgName() + "'";
			SQLiteDatabase customDb = null;
			Cursor cursor = null;
			try {
				customDb = mDataBase.getWritableDatabase();
				cursor = customDb.rawQuery(sql, null);
				if(cursor!=null&&cursor.moveToFirst()){
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (cursor != null) {
					cursor.close();
				}
				if (customDb != null) {
					customDb.close();
				}
			}
		}
	}
	public boolean IsTableEmpty() {
		boolean isEmpty = true;
		synchronized (mLock) {
			if (mDataBase.queryCount(CustomMessageTb.class) > 0) {
				isEmpty = false;
			}
		}
		return isEmpty;
	}
}
